import { MessageListParam } from '@/api/custcare/talk/BackUserModel'
import { getMessageListApi } from '@/api/custcare/talk/back_user'
import { StatusCode } from '@/http/request'
import { IMessage } from '@/store/type'
import { DialogModel } from '@/types/BaseType'
import { formatDate } from '@/utils/filters'
import { nextTick, onMounted, reactive, ref } from 'vue'

export default function useRecord(
    dialogModel: DialogModel,
    onShow: any,
    onClose: any
) {
    const mainLayoutHeight = ref(0)

    const messageList = reactive({
        list: Array<IMessage>()
    })

    const onConfirm = () => {
        onClose()
    }

    // 展示弹框
    const show = async (type: string, custcare: any, visitorInfo: any) => {
        dialogModel.title = visitorInfo.client_ip + '的消息记录'
        // console.log('访客的消息记录 客服:', custcare)
        // console.log('访客的消息记录 游客:', visitorInfo)
        const param = reactive<MessageListParam>({
            channel_id: custcare.channel_id
        })
        let res = await getMessageListApi(param)
        if (res && res.code == StatusCode.Success) {
            // console.log('消息列表：', res.data.list)
            messageList.list = []
            if (res.data.list) {
                res.data.list.forEach((item: any) => {
                    let msg_type = 'right'
                    if (item.visitor_id == visitorInfo.id) {
                        msg_type = 'left'
                    }
                    const iMessage = reactive<IMessage>({
                        msg_type: msg_type, // left / right
                        uuid: visitorInfo.uuid,
                        nickname: custcare.nickname,
                        avatar: custcare.avatar,
                        client_ip: visitorInfo.client_ip,
                        type: item.type,
                        content: item.content,
                        send_time: item.created_at,
                        send_time_text: formatDate(item.created_at)
                    })
                    messageList.list.push(iMessage)
                })
                // console.log(messageList.list)
                setScrollTop()
            }
        }

        // 显示弹框
        onShow()
    }

    const setScrollTop = () => {
        setTimeout(() => {
            const target = document.querySelector('#messageList')
            if (target) {
                target.scrollTo(0, target.scrollHeight)
            }
        }, 100)
    }

    const emotion = (res: string) => {
        let word = res.replace(/\:/gi, '')
        return `<img class="emotion" width="32px" height="32px" src="/src/assets/emo/streamlinehq-${word}-smiley-people-102.png">`
    }

    onMounted(() => {
        nextTick(() => {
            mainLayoutHeight.value = window.innerHeight - 200
        })
    })

    return {
        messageList,
        onConfirm,
        show,
        emotion
    }
}
